//License: Artistic License v2.0, http://opensource.org/licenses/Artistic-2.0

package main

import (
	"io/ioutil"
	"regexp"
	"strings"
)

var mobileRegexp regexp.Regexp

//IsMobile checks an input string against the mobile regexp
//constructed in SetMobileRegexp beforehand.  The input string is typically the
//user browser's signature / agent.  If regexp matches, then IsMobile returns true.
//For example: IsMobile(http.Request.UserAgent())
func IsMobile(userAgent string) bool {
	return mobileRegexp.MatchString(strings.ToLower(userAgent))
}

//SetMobileDetection loads Go regular expression from a text file (fname) into memory
//for the consumption of IsMobile. You typically call it during app start up,
//not during runtime, since it reads from disk.
//For example: The text file may contain "android.+mobile|ip(hone|od)".
//func SetMobileDetection(fname string) (regexp.Regexp, error) {
func SetMobileDetection(fname string) error {
	byteArray, err := ioutil.ReadFile(fname)
	if err != nil {
		return err
	}
	re, err := regexp.Compile(string(byteArray))
	if err != nil {
		return err
	}
	mobileRegexp = *re
	return nil
}

/*func SetupMobileDetection(fname string) (func (string) bool) {

	//not more pragmatic than using "unexported" global var mobileRegexp
	//so this approach is dropped but this is a valid alternative

	byteArray, err := ioutil.ReadFile(fname)
	if err != nil {
		return nil
	}
	re, err := regexp.Compile(string(byteArray))
	if err != nil {
		return nil
	}
	if err != nil {
		log.Println(err)
		return nil
	}
	return func (userAgent string) bool {
		return re.MatchString(strings.ToLower(userAgent))
	} 
} */

//Copyright: Slamet Hendry
